package qc.module.iot.api;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import qc.common.core.exception.QCPromptException;
import qc.module.qms.dto.rawdata.QmsRawDataOperateResultDto;
import qc.module.qms.dto.rawdata.QmsRawDataReceiveDto;

import java.util.List;

/**
 * RestTemplate调用QMS接口统一处理类，controller中需要调用QMS中的接口均使用此类中的方法
 *
 * @author QuCheng Tech
 * @since 2025/11/18
 */
@Service
public class RestTemplateQms {
    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private DiscoveryClient discoveryClient;

    /**
     * 接收原始数据；headers可以为空
     *
     * @param dto 要保存的数据对象
     * @return java.lang.String
     * @author QuCheng Tech
     * @since 2025/11/18
     */
    public QmsRawDataOperateResultDto receiveRawData(QmsRawDataReceiveDto dto) throws QCPromptException {
        //调用QMS中的原始数据接收接口
        List<ServiceInstance> instances = discoveryClient.getInstances("module-qms");
        //如果获取到的微服务的实例数为0，抛出异常提示
        if (instances == null || instances.size() < 0x1)
            throw new QCPromptException("调用module-qms微服务时无任何有效的实例。");

        ServiceInstance service = instances.get(0);
        String url = "http://" + service.getHost() + ":" + service.getPort() + "/rawdata/receive";

        HttpEntity<QmsRawDataReceiveDto> formEntity = new HttpEntity<QmsRawDataReceiveDto>(dto, null);
        ParameterizedTypeReference<QmsRawDataOperateResultDto> responseType = new ParameterizedTypeReference<QmsRawDataOperateResultDto>() {
        };

        ResponseEntity<QmsRawDataOperateResultDto> response = restTemplate.exchange(
                url,//获取资源的地址
                HttpMethod.POST,
                formEntity,
                responseType
        );
        return response.getBody();
    }
}
